<script setup>
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout.vue';
import PrimaryButton from '@/Components/PrimaryButton.vue';
import { Head, Link, useForm, router } from '@inertiajs/vue3';
import { computed } from 'vue';

const props = defineProps({
    bar: {
        type: Object,
        required: true,
    },
    isMember: {
        type: Boolean,
        default: false,
    },
    userRole: {
        type: String,
        default: null,
    },
    posts: {
        type: Object,
        default: null,
    },
    filters: {
        type: Object,
        default: () => ({}),
    },
});

const joinForm = useForm({});
const leaveForm = useForm({});
const likeForms = {};
const favoriteForms = {};

const handleJoin = () => {
    joinForm.post(route('bars.join', props.bar.id));
};

const handleLeave = () => {
    leaveForm.post(route('bars.leave', props.bar.id));
};

const handleSort = (sort) => {
    router.get(route('bars.show', props.bar.slug), { sort }, {
        preserveState: true,
        preserveScroll: true,
    });
};

const handleLike = (post) => {
    if (!likeForms[post.id]) {
        likeForms[post.id] = useForm({});
    }
    likeForms[post.id].post(route('posts.like', post.slug), {
        preserveScroll: true,
    });
};

const handleFavorite = (post) => {
    if (!favoriteForms[post.id]) {
        favoriteForms[post.id] = useForm({});
    }
    favoriteForms[post.id].post(route('posts.favorite', post.slug), {
        preserveScroll: true,
    });
};

const getBarAvatar = (bar) => {
    if (bar.avatar) {
        return bar.avatar.startsWith('http') ? bar.avatar : `/storage/${bar.avatar}`;
    }
    return `https://api.dicebear.com/7.x/shapes/svg?seed=${bar.name}`;
};

const getUserAvatar = (user) => {
    if (user?.avatar) {
        return user.avatar.startsWith('http') ? user.avatar : `/storage/${user.avatar}`;
    }
    return `https://api.dicebear.com/7.x/avataaars/svg?seed=${user?.name || 'user'}`;
};

const formatNumber = (num) => {
    if (num >= 10000) {
        return (num / 10000).toFixed(1) + '万';
    }
    return num.toString();
};

const formatTime = (time) => {
    if (!time) return '';
    const date = new Date(time);
    const now = new Date();
    const diff = now - date;
    const minutes = Math.floor(diff / 60000);
    const hours = Math.floor(diff / 3600000);
    const days = Math.floor(diff / 86400000);

    if (minutes < 1) return '刚刚';
    if (minutes < 60) return `${minutes}分钟前`;
    if (hours < 24) return `${hours}小时前`;
    if (days < 7) return `${days}天前`;
    return date.toLocaleDateString('zh-CN');
};

const currentSort = computed(() => props.filters?.sort || 'latest');
</script>

<template>
    <Head :title="bar.name" />

    <AuthenticatedLayout>
        <div class="space-y-6">
            <!-- 贴吧信息卡片 -->
            <div class="bg-card text-card-foreground flex flex-col gap-4 sm:gap-6 rounded-xl border py-4 sm:py-6 shadow-sm">
                <div class="px-4 sm:px-6">
                    <div class="flex flex-col sm:flex-row items-start gap-3 sm:gap-4">
                        <img
                            :src="getBarAvatar(bar)"
                            :alt="bar.name"
                            class="w-16 h-16 sm:w-20 sm:h-20 rounded-lg flex-shrink-0"
                        />
                        <div class="flex-1 min-w-0">
                            <h1 class="text-2xl sm:text-3xl font-bold mb-2 break-words">{{ bar.name }}</h1>
                            <p class="text-muted-foreground mb-3 sm:mb-4 break-words">{{ bar.description || '暂无简介' }}</p>
                            <div class="flex flex-wrap gap-3 sm:gap-6 text-sm text-muted-foreground">
                                <span>{{ formatNumber(bar.member_count) }} 成员</span>
                                <span>{{ formatNumber(bar.post_count) }} 帖子</span>
                                <span v-if="bar.owner" class="break-words">吧主：{{ bar.owner.nickname || bar.owner.name }}</span>
                            </div>
                        </div>
                        <div v-if="$page.props.auth?.user" class="flex-shrink-0 w-full sm:w-auto">
                            <PrimaryButton
                                v-if="!isMember"
                                @click="handleJoin"
                                :disabled="joinForm.processing"
                                class="h-9 px-4"
                            >
                                <svg class="h-4 w-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
                                </svg>
                                关注
                            </PrimaryButton>
                            <button
                                v-else
                                @click="handleLeave"
                                :disabled="leaveForm.processing || userRole === 'owner'"
                                class="inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all border bg-background shadow-sm hover:bg-accent hover:text-accent-foreground h-9 px-4 py-2"
                                :class="{ 'opacity-50 cursor-not-allowed': userRole === 'owner' }"
                            >
                                已关注
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 帖子列表区域 -->
            <div class="bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm">
                <div class="px-6">
                    <div class="flex justify-between items-center mb-4">
                        <h2 class="text-xl font-bold">全部帖子</h2>
                        <Link
                            v-if="isMember || userRole === 'owner'"
                            :href="route('posts.create', { bar: bar.slug })"
                            class="inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all bg-primary text-primary-foreground shadow-sm hover:bg-primary/90 h-9 px-4 py-2"
                        >
                            <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
                            </svg>
                            发帖
                        </Link>
                    </div>
                    
                    <!-- 排序筛选栏 -->
                    <div class="bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px] mb-6">
                        <button
                            @click="handleSort('latest')"
                            class="inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-3 py-1 text-sm font-medium whitespace-nowrap transition-all"
                            :class="currentSort === 'latest' 
                                ? 'bg-background text-foreground shadow-sm' 
                                : 'text-muted-foreground'"
                        >
                            最新
                        </button>
                        <button
                            @click="handleSort('hot')"
                            class="inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-3 py-1 text-sm font-medium whitespace-nowrap transition-all"
                            :class="currentSort === 'hot' 
                                ? 'bg-background text-foreground shadow-sm' 
                                : 'text-muted-foreground'"
                        >
                            最热
                        </button>
                        <button
                            @click="handleSort('essence')"
                            class="inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-3 py-1 text-sm font-medium whitespace-nowrap transition-all"
                            :class="currentSort === 'essence' 
                                ? 'bg-background text-foreground shadow-sm' 
                                : 'text-muted-foreground'"
                        >
                            精华
                        </button>
                    </div>
                    
                    <!-- 帖子列表 -->
                    <div v-if="posts && posts.data && posts.data.length" class="space-y-4">
                        <div
                            v-for="post in posts.data"
                            :key="post.id"
                            class="bg-card text-card-foreground rounded-xl border p-4 shadow-sm hover:shadow-md transition-shadow cursor-pointer"
                            :class="post.is_pinned ? 'border-2 border-primary/30' : ''"
                        >
                            <div class="flex gap-4">
                                <Link
                                    v-if="post.user"
                                    :href="route('users.show', post.user?.username || post.user?.id)"
                                    class="flex-shrink-0 hover:opacity-80 transition-opacity"
                                >
                                    <img
                                        :src="getUserAvatar(post.user)"
                                        :alt="post.user?.nickname || post.user?.name"
                                        class="w-10 h-10 rounded-full"
                                    />
                                </Link>
                                <img
                                    v-else
                                    src="https://api.dicebear.com/7.x/avataaars/svg?seed=anonymous"
                                    alt="匿名用户"
                                    class="w-10 h-10 rounded-full flex-shrink-0"
                                />
                                <div class="flex-1 min-w-0">
                                    <div class="flex items-center gap-2 mb-1">
                                        <span v-if="post.is_pinned" class="inline-flex items-center justify-center rounded-md border border-transparent bg-primary text-primary-foreground px-2 py-0.5 text-xs font-medium">
                                            📌 置顶
                                        </span>
                                        <span v-if="post.is_essence" class="inline-flex items-center justify-center rounded-md border border-transparent bg-secondary text-secondary-foreground px-2 py-0.5 text-xs font-medium">
                                            ⭐ 精华
                                        </span>
                                        <Link
                                            v-if="post.user"
                                            :href="route('users.show', post.user?.username || post.user?.id)"
                                            class="font-semibold hover:opacity-80 transition-opacity"
                                        >
                                            {{ post.user?.nickname || post.user?.name }}
                                        </Link>
                                        <span v-else class="font-semibold">匿名用户</span>
                                        <span class="text-sm text-muted-foreground ml-auto">{{ formatTime(post.created_at) }}</span>
                                    </div>
                                    <Link :href="route('posts.show', post.slug)" class="block">
                                        <h3 class="font-bold text-lg mb-2 hover:opacity-80 transition-opacity">{{ post.title }}</h3>
                                        <p class="text-muted-foreground line-clamp-2 mb-3">{{ post.content }}</p>
                                    </Link>
                                    <div class="flex items-center gap-4 text-sm text-muted-foreground">
                                        <button
                                            v-if="$page.props.auth?.user"
                                            @click.prevent="handleLike(post)"
                                            class="flex items-center gap-1 hover:text-gray-900 transition-colors"
                                            :class="post.is_liked ? 'text-red-500' : ''"
                                        >
                                            <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
                                            </svg>
                                            {{ formatNumber(post.like_count) }}
                                        </button>
                                        <span class="flex items-center gap-1">
                                            <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
                                            </svg>
                                            {{ formatNumber(post.reply_count || 0) }}
                                        </span>
                                        <button
                                            v-if="$page.props.auth?.user"
                                            @click.prevent="handleFavorite(post)"
                                            class="flex items-center gap-1 hover:text-gray-900 transition-colors"
                                            :class="post.is_favorited ? 'text-yellow-500' : ''"
                                        >
                                            <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z" />
                                            </svg>
                                            收藏
                                        </button>
                                        <span class="flex items-center gap-1">
                                            <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                                            </svg>
                                            {{ formatNumber(post.views) }}
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div v-else class="text-center py-12 text-muted-foreground">
                        <p>暂无帖子</p>
                        <p class="text-sm mt-2">成为第一个发帖的用户吧！</p>
                    </div>

                    <!-- 分页控件 -->
                    <div v-if="posts && posts.links && posts.links.length > 3" class="px-6 pt-6 border-t mt-4">
                        <div class="flex items-center justify-center gap-2">
                            <Link
                                v-for="(link, index) in posts.links"
                                :key="index"
                                :href="link.url || '#'"
                                v-html="link.label"
                                class="inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-all h-9 px-3 py-2"
                                :class="link.active
                                    ? 'bg-primary text-primary-foreground shadow-sm'
                                    : link.url
                                        ? 'border bg-background shadow-sm hover:bg-accent hover:text-accent-foreground'
                                        : 'text-muted-foreground cursor-not-allowed pointer-events-none'"
                            />
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </AuthenticatedLayout>
</template>
